package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class MLSTHandle implements Handle {
	FtpSession ftpSession;
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss.SSS", Locale.ENGLISH);

	public MLSTHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String fileName=line.substring(line.indexOf(" "));
		String path = PathConvert.toServerPath(ftpSession.getRootDir(), ftpSession.currentDir+"/"+fileName.trim());
		File file = new File(path.trim());
		os.write(("250- Listing "+fileName+"\r\n").getBytes());
		os.flush();
		if(!file.exists()){
			os.write("250 End\r\n".getBytes());
			os.flush();
			return;
		}
		String template = "Type=#{dir};#{size}Modify=#{time};Perm=#{perm}; #{fileName}\r\n";
		long time = file.lastModified();
		Date date = new Date(time);
		template = template.replace("#{time}", sdf.format(date));
		template = template.replace("#{fileName}", file.getName());
		
		if (file.isDirectory()) {
			template = template.replace("#{dir}", "dir");
			template = template.replace("#{perm}", "elmc");
			template = template.replace("#{size}", "");
		} else {
			template = template.replace("#{dir}", "file");
			template = template.replace("#{perm}", "rw");
			template = template.replace("#{size}", "Size=#{fileSize};");
			template = template.replace("#{fileSize}", Long.toString(file.length()));
		}
		os.write(template.getBytes());
		os.write("250 End\r\n".getBytes());
		os.flush();
	}
}